<%@ page pageEncoding="utf-8" contentType="image/jpeg" 
import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*,cn.util.ColorTools" %>
   <%
   //设置页面不缓存
   response.setHeader("Pragma","No-cache");
   response.setHeader("Cache-Control","no-cache");
   response.setDateHeader("Expires", 0);
   
   // 设置图片的长宽
   int width=116, height=30;
   //设置备选汉字，剔除一些不雅的汉字
   String base = "1";
   //备选汉字的长度
   int length = base.length();
   
   //创建内存图像
   BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
   // 获取图形上下文
   Graphics g = image.getGraphics();
   
   //创建随机类的实例
   Random random = new Random();
   
   // 设定图像背景色(因为是做背景，所以偏淡)
   g.setColor(ColorTools.getRandColor(random,200,250));
   g.fillRect(0, 0, width, height);
   
   //备选字体
   String[] fontTypes = {"\u5b8b\u4f53"};
   int fontTypesLength = fontTypes.length;
   
   //在图片背景上增加噪点
   g.setColor(ColorTools.getRandColor(random,160,200));
   g.setFont(new Font("Times New Roman",Font.PLAIN,14));
   for (int i=0;i<6;i++)
   {
   g.drawString("*********************************************",0,5*(i+2));
   }
   
   //取随机产生的认证码(4个汉字)
   
   //保存生成的汉字字符串
   String sRand="";
   for (int i=0;i<4;i++)
   {
   int start = random.nextInt(length);
   String rand=base.substring(start,start+1);
   sRand+=rand;
   
   //设置字体的颜色
   g.setColor(ColorTools.getRandColor(random,10,150));
   //设置字体
   g.setFont(new Font(fontTypes[random.nextInt(fontTypesLength)],Font.BOLD,18 + random.nextInt(6)));
   //将此汉字画到图片上
   g.drawString(rand,24*i+ 10 + random.nextInt(8),24);
   }
   
   //将认证码存入session
   session.setAttribute("rand",sRand);
   
   g.dispose();
   
   //输出图象到页面
   ImageIO.write(image, "JPEG", response.getOutputStream());
   out.clear();
   out = pageContext.pushBody();
   %> 